<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="承运商" prop="companyName">
            <el-input
                v-model="queryParams.companyName"
                placeholder="请输入承运商名称"
                clearable
            />
        </el-form-item>
        <el-form-item label="所在城市" prop="originPlace">
            <provice-select @changeValue="queryChangeValue"></provice-select>
            <!-- <el-select v-model="queryParams.province" filterable placeholder="请选择省"  style=" width:165px;"  @change="getCitys" clearable>
                <el-option v-for="item in provinces" :key="item.id" :label="item.cityName"
                    :value="item.id"></el-option>
            </el-select>

            <el-select v-model="queryParams.city" filterable placeholder="请选择市" style=" width:165px;margin-left: 17px" clearable @change="changeCityValue($event, 'province')">
                <el-option v-for="item in queryCitys" :key="item.id" :label="item.cityName"
                    :value="item.id"></el-option>
            </el-select> -->
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="queryParams.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="queryParams.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <!-- 权限 -->
        <!--  v-hasPermi="['system:menu:add']" -->
        <!-- v-hasPermi="['system:menu:delete']" -->
        <el-col :span="1.5">
            <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button>
            <el-button
            type="primary"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="deleteIds"
            >删除</el-button>
            <!-- <el-button
            type="primary"
            plain
            icon="el-icon-s-check"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:menu:examine']"
            >审核</el-button> -->
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="tagList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="承运商名称" align="center" prop="companyName">
            <template slot-scope="{row}" >
                <span  @click="handleUpdate(row, 1)" style="color: #1890ff;text-decoration: underline 1px solid #1890ff;cursor: pointer;">{{ row.companyName }}</span>
            </template>
        </el-table-column>
        <el-table-column label="用户" align="center" prop="nickName">
          <template slot-scope="{row}">
            <span>{{row.nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" align="center" prop="phoneNumber">
          <template slot-scope="{row}">
            <span>{{row.phoneNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="法人" align="center" prop="legalPersonName"></el-table-column>
        <el-table-column label="法人电话" align="center" prop="legalPersonPhone"></el-table-column>
        <!-- <el-table-column label="是否审核" align="center" prop="isApproved">
            <template slot-scope="{row}">
                <span>{{ row.isApproved == 0 ? '否' : row.isApproved == 1 ? '审核通过' : '作废' }}</span>
            </template>
        </el-table-column> -->
        <el-table-column label="所在城市" align="center">
            <template slot-scope="{row}">
                <span>{{ fomatterAdressName(row.province) }} / {{ fomatterAdressName(row.city) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="物流网点数" align="center">
            <template slot-scope="{row}" >
                <span  @click="handleUpdate(row)" style="color: #1890ff;text-decoration: underline 1px solid #1890ff;cursor: pointer;">{{ row.crmNetworkCounts }}</span>
            </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="{row}">
                <span>{{ row.createTime && row.createTime.slice(0, 10) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="toTop(scope.row)"
          >置顶</el-button>
            <!-- v-hasPermi="['system:menu:edit']" -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, '2')"
          >修改</el-button>
          <!-- v-hasPermi="['system:menu:remove']" -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <!-- v-hasPermi="['system:menu:edit']" -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >查询网点</el-button>
        </template>
      </el-table-column>
      </el-table>
      
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改标签管理对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
        <div v-if="isOpeartType == '1'" class="form-info">
            <div class="form-info-item form-info-row">
                承运商名称: {{ form.companyName }}
            </div>
            <div class="form-info-item">
                承运商法人: {{ form.legalPersonName }}
            </div>
            <div class="form-info-item">
                承运商法人电话: {{ form.legalPersonPhone }}
            </div>
            <div class="form-info-item">
                业务负责人姓名: {{ form.businessLeaderName }}
            </div>
            <div class="form-info-item">
                业务负责人电话: {{ form.businessLeaderPhone }}
            </div>
            <div class="form-info-item form-info-row">
                所在地址: {{ form.provinceName }} / {{  form.cityName }} / {{   form.districtName }}
            </div>
            <div class="form-info-item" v-if="form.businessLicense && form.businessLicense != ''">
                <div class="row-label">营业执照:</div>
                <el-image class="image-box" :preview-src-list="[baseUrl + form.businessLicense]" :src="baseUrl + form.businessLicense" alt=""/>
            </div>
            <div class="form-info-item" v-if="form.roadTransportPermit && form.roadTransportPermit != ''">
                <div class="row-label">道路运输许可证:</div>
                <el-image class="image-box" :preview-src-list="[baseUrl + form.roadTransportPermit]" :src="baseUrl + form.roadTransportPermit" alt=""/>
            </div>
            <div class="form-info-item" v-if="form.legalPersonIdCardFront && form.legalPersonIdCardFront != ''">
                <div class="row-label">身份证正面:</div>
                <el-image class="image-box" :preview-src-list="[baseUrl + form.legalPersonIdCardFront]" :src="baseUrl + form.legalPersonIdCardFront" alt=""/>
            </div>
            <div class="form-info-item" v-if="form.legalPersonIdCardBack && form.legalPersonIdCardBack != ''">
                <div class="row-label">身份证反面:</div>
                <el-image class="image-box" :preview-src-list="[baseUrl + form.legalPersonIdCardBack]" :src="baseUrl + form.legalPersonIdCardBack" alt=""/>
            </div>
            <div class="form-info-item" v-if="form.businessLeaderIdCardFront && form.businessLeaderIdCardFront != ''">
                <div class="row-label">业务负责人身份证正面:</div>
                <el-image class="image-box" :preview-src-list="[baseUrl + form.businessLeaderIdCardFront]" :src="baseUrl + form.businessLeaderIdCardFront" alt=""/>
            </div>
            <div class="form-info-item" v-if="form.businessLeaderIdCardBack && form.businessLeaderIdCardBack != ''">
                <div class="row-label">业务负责人身份证反面:</div>
                <el-image class="image-box" :preview-src-list="[baseUrl + form.businessLeaderIdCardBack]" :src="baseUrl + form.businessLeaderIdCardBack" alt=""/>
            </div>
            <div class="form-info-item form-info-row" v-if="form.operationSitePhotos && form.operationSitePhotos != ''">
                <div class="row-label">经营场地及车辆照片:</div>
                <el-image 
                    class="image-box" 
                    :preview-src-list="form.operationSitePhotos.split(',').map(ele => baseUrl + ele)"  
                    v-for="item in form.operationSitePhotos.split(',')" :key="item" :src="baseUrl + item" alt=""/>
            </div>
        </div>
        <el-form v-else ref="form" :model="form" :rules="formRule" :inline="true" label-width="120px" class="form-inline">
            <el-form-item label="承运商名称:" prop="companyName">
                <el-input v-model="form.companyName" placeholder="请输入承运商名称" style="width: 400px;"/>
            </el-form-item>
            <el-form-item label="承运商法人:" prop="legalPersonName">
                <el-input v-model="form.legalPersonName" placeholder="请输入承运商联系人" />
            </el-form-item>
            <el-form-item label="承运商法人电话:" prop="legalPersonPhone">
                <el-input v-model="form.legalPersonPhone" placeholder="请输入承运商联系人电话" maxlength="11"/>
            </el-form-item>
            <el-form-item label="业务负责人姓名:" prop="businessLeaderName">
                <el-input v-model="form.businessLeaderName" placeholder="请输入业务负责人姓名" />
            </el-form-item>
            <el-form-item label="业务负责人电话:" prop="businessLeaderPhone">
                <el-input v-model="form.businessLeaderPhone" placeholder="请输入业务负责人电话" maxlength="11"/>
            </el-form-item>
            <!-- <el-form-item label="紧急联系人电话:" prop="emergencyContactPhone">
                <el-input v-model="form.emergencyContactPhone" placeholder="请输入紧急联系人电话" maxlength="11"/>
            </el-form-item> -->
            <el-form-item label="所在地址:">
                <provice-select :defaultCity="defaultCity" :isShowDistrict="true" @changeValue="changeValue"></provice-select>
            </el-form-item>
            <el-form-item label="详细地址:">
                <el-input v-model="form.location" placeholder="请输入详细地址" style="width: 600px;"/>
            </el-form-item>
            <el-form-item class="row" label="营业执照:" prop="businessLicense">
                <image-upload v-model="form.businessLicense" :limit="1" />
            </el-form-item>
            <el-form-item class="row" label="道路运输许可证:" prop="roadTransportPermit">
                <image-upload v-model="form.roadTransportPermit" :limit="1"/>
            </el-form-item>
            <el-form-item class="row" label="身份证正面:">
                <image-upload v-model="form.legalPersonIdCardFront" :limit="1"/>
            </el-form-item>
            <el-form-item class="row" label="身份证反面:">
                <image-upload v-model="form.legalPersonIdCardBack" :limit="1"/>
            </el-form-item>
            <el-form-item class="row" label="业务负责人身份证正面:" label-width="200px">
                <image-upload v-model="form.businessLeaderIdCardFront" :limit="1"/>
            </el-form-item>
            <el-form-item class="row" label="业务负责人身份证反面:" label-width="200px">
                <image-upload v-model="form.businessLeaderIdCardBack" :limit="1"/>
            </el-form-item>
            <el-form-item class="row" label="经营场地及车辆照片(最多6张):" prop="img" label-width="500px">
                <image-upload v-model="form.operationSitePhotos" :limit="6"/>
            </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isOpeartType == '2'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import Enmu from "../../../../utils/enmu";
  import { getCompaniesistList, addCompaniesist, editCompaniesist, deleteCompaniesist, certificaInfo, companiesOnTop } from "@/api/crm/settleIn";
  import {forrmatterEnmu} from "@/utils/index"
  import ProviceSelect from "@/components/ProviceSelect/index.vue"
  import {mapGetters} from "vuex"
  var validatePass = (rule, value, callback) => {
    if (value) {
        let r = /^1[34578]\d{9}$/.test(value);
        if(!r) {
            callback(new Error('请输入正确的手机号码'));
        } else {
            callback();
        }
    } else {
        callback();
    }
};
  export default {
    name: "Tag",
    data() {
      return {
        baseUrl: process.env.VUE_APP_BASE_API,
        provinces: [],
        cityslist: [],
        regionslist: [],
        queryCitys: [],
        addCitysList: [],
        addRegionslist: [],
        Enmu,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 标签管理表格数据
        tagList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            province: '',
            city: '',
            companyName: '',
            startTime: '',
            endTime: ''
        },
        // 报价列表
        quotationList: [],
        form: {
            companyName: '',
            legalPersonName: '',
            legalPersonPhone: '',
            businessLeaderName: '',
            businessLeaderPhone: '',
            emergencyContactPhone: '',
            province: '',
            city: '',
            district: '',
            businessLicense: '',
            roadTransportPermit: '',
            legalPersonIdCardFront: '',
            legalPersonIdCardBack: '',
            businessLeaderIdCardFront: '',
            businessLeaderIdCardBack: '',
            operationSitePhotos: '',
            location: ''
        },
        rules: {},
        ids: [],
        isOpeartType: '2',
        defaultCity: {}
      };
    },
    created() {
      this.getList();
    },
    components: {ProviceSelect},
    computed: {
        formRule() {
            // 1 审核 2 修改
            if(this.isOpeartType == '1') {
                return this.examineRule();
            } else {
                return this.editRule();
            }
        },
        ...mapGetters(['allCityList'])
    },
    methods: {
        forrmatterEnmu,
         // 省市区转换成中文
         fomatterAdressName(code) {
            if(!code || code == "") return "";
          let index = this.allCityList.findIndex(ele => ele.id == code);
          return index > -1 ? this.allCityList[index].cityName : code;
        },
        changeValue(values) {
            this.form.province = values[0];
            this.form.city = values[1];
            this.form.district = values[2];
        },
        queryChangeValue(values) {
            console.log(values)
            this.queryParams.province = values[0];
            this.queryParams.city = values[1];
        },
      /** 查询标签管理列表 */
      getList() {
        this.loading = true;
        getCompaniesistList({...this.queryParams, approvedStatus: 1}).then(response => {
          this.tagList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
    reset() {
        console.log("000")
        this.form = {
            id: '',
            companyName: '',
            legalPersonName: '',
            legalPersonPhone: '',
            businessLeaderName: '',
            businessLeaderPhone: '',
            emergencyContactPhone: '',
            province: '',
            city: '',
            district: '',
            businessLicense: '',
            roadTransportPermit: '',
            legalPersonIdCardFront: '',
            legalPersonIdCardBack: '',
            businessLeaderIdCardFront: '',
            businessLeaderIdCardBack: '',
            operationSitePhotos: '',
            location: ''
        };
        this.resetForm("form");
    },
    handleDelete(row) {
        this.$confirm('确定删除此承运商', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            deleteCompaniesist([row.id]).then(res => {
                if(res.code == 200) {
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleUpdate(row, flag) {
        if(!flag) {
            this.$router.push({
                path: '/settleIn/network/index',
                query: {
                    id: row.id
                }
            })
            return;
        }
        this.isOpeartType = flag;
        Object.keys(this.form).forEach(ele => {
            if(ele == 'province' || ele == 'city' || ele == 'district') {
                if(row[ele] && row[ele] != '' && row[ele] != null) {
                    this.$set(this.form, ele, row[ele] - 0);
                }
            } else {
                this.$set(this.form, ele, row[ele]);
            }  
        });
        this.defaultCity = {
            province: row.province,
            city: row.city,
            district: row.district,
        }
        console.log(this.defaultCity)
        this.addCitysList = this.cityslist.filter(item => parseInt(item.parentId) == parseInt(this.form.province));
        this.addRegionslist = this.regionslist.filter(item => parseInt(item.parentId) == parseInt(this.form.city));
        this.$set(this.form, 'id', row.id);
        if(flag == '1') {
            this.$set(this.form, 'provinceName', this.fomatterAdressName(row.province));
            this.$set(this.form, 'cityName', this.fomatterAdressName(row.city));
            this.$set(this.form, 'districtName', this.fomatterAdressName(row.district));
        }
        this.open = true;
    },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleAdd() {
        this.reset();
        this.open = true;
      },
      submitForm() {
            console.log(this.form);
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if(this.form.id !== '') {
                        editCompaniesist(this.form).then(res => {
                            if(res.code == 200) {
                                this.$modal.msgSuccess("修改成功成功");
                                this.open = false;
                                this.getList();
                                this.reset();
                            }
                        })
                    } else {
                        addCompaniesist({...this.form, entryMode: 1, isApproved: 2}).then(res => {
                            if(res.code == 200) {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                                this.reset();
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
            
            
        },
         // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
      },
      deleteIds() {
        this.$confirm('确定删除所购选的承运商', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            deleteCompaniesist(this.ids).then(res => {
                if(res.code == 200) {
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editRule() {
        return {
            legalPersonPhone: [
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            businessLeaderPhone: [
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            emergencyContactPhone: [
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
        }
      },
      examineRule() {
        let rule = {
            companyName: [
                { required: true, message: '请输入承运商名称', trigger: 'change' }
            ],
            legalPersonName: [
                { required: true, message: '请输入承运商法人', trigger: 'change' }
            ],
            legalPersonPhone: [
                { required: true, message: '请输入承运商法人电话', trigger: 'change' },
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            businessLeaderName: [
                { required: true, message: '请输入业务负责人姓名', trigger: 'change' }
            ],
            businessLeaderPhone: [
                { required: true, message: '请输入业务负责人电话', trigger: 'change' },
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            emergencyContactPhone: [
                { required: true, message: '请输入紧急联系人电话', trigger: 'change' },
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            province: [
                { required: true, message: '请选择省', trigger: 'change' }
            ],
            city: [
                { required: true, message: '请选择市', trigger: 'change' }
            ],
            district: [
                { required: true, message: '请选择区', trigger: 'change' }
            ],
        };
        return rule;
      },
      checkoutAdmin() {
        let keys = ['companyName', 'legalPersonName', 'legalPersonPhone', 'businessLeaderName', 'businessLeaderPhone', 'emergencyContactPhone', 'province', 'city', 'district'];
        for(let i = 0; i < keys.length; i++) {
            if(this.form[keys[i]] == "") {
                this.$modal.msgError("必填项不能为空，请修改必填项");
                return false;
            }
        }
        return true;
      },
      examine() {
        // this.$refs['form'].validate((valid) => {
        //     if (valid) {
        //         console.log(this.form)
        //         certificaInfo({id: this.form.id, entryType: 1, companyName: this.form.companyName}).then(res => {
        //             if(res.code == 200) {
        //                 this.$modal.msgSuccess("审核成功");
        //                 this.open = false;
        //                 this.getList();
        //                 this.reset();
        //             }
        //         })
        //     } else {
        //         this.$modal.msgError("必填项不能为空，请修改必填项");
        //         return false;
        //     }
        // });
        if(!this.checkoutAdmin()) return;
        certificaInfo({id: this.form.id }).then(res => {
            if(res.code == 200) {
                this.$modal.msgSuccess("审核成功");
                this.open = false;
                this.getList();
                this.reset();
            }
        })
      },
      toTop(item) {
        companiesOnTop({id: item.id, isTop: 1}).then(res => {
            if(res.code == 200) {
                this.$modal.msgSuccess("置顶成功");
                this.queryParams.pageNum = 1;
                this.getList();
            }
        })
      }
        
    },
     
    
  };
  </script>
  <style scoped>
  .form-inline {
    display: flex;
    flex-wrap: wrap;
  }
  .form-info {
    display: flex;
    width: 800px;
    flex-wrap: wrap;
  }
  .form-info .form-info-item {
    margin-bottom: 15px;
  }
  
  .form-info-item {
    width: 49%;
    flex: 0 0 49%;
    /* height: 40px; */
  }
  .form-info .form-info-item.form-info-row {
    width: 100%;
    flex: 0 0 100%;
  }
  .form-info .row-label {
    margin-bottom: 5px;
  }
  .form-info .image-box {
    width: 100px;
    height: 100px;
    border-radius: 5px;
    margin-right: 10px;
  }
  .form-info-item span {
    color: red;
  }
  .form-info-item img {
    width: 100px;
    height: 100px;
    vertical-align: top;
    margin-left: 10px;
  }
  </style>
  